<script lang="ts" setup>
import { onMounted, reactive, defineEmits } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { ElMessage , ElMessageBox} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios';

const emit = defineEmits(['changePage']);
const router = useRouter()
const state = reactive({
    imageUrl: '',
    showUpload: false,
    userId: '',
    username: '爱丽丝V**n',
    telephone: '19959575300',
    userInfo: {

    }
});

const handleAvatarSuccess = (response, uploadFile) => {
    state.imageUrl = URL.createObjectURL(uploadFile.raw)
}



const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

// 请求用户 ID
const fetchUserId = async (uid) => {
    try {
        const response = await axios.get(`http://localhost:8100/api/getUserId?uid=${uid}`); // 将 uid 作为查询参数传入
        state.userId = response.data.userId; // 假设响应中有 userId 字段
        console.log(response)
    } catch (error) {
        ElMessage.error('Failed to fetch user ID!');
    }
};

// 使用 onMounted 在组件挂载时调用 fetchUserId
onMounted(() => {
    const route = useRoute(); // 获取路由信息
    const uid = route.query.uid; // 从 URL 中获取 uid
    fetchUserId(uid); // 传入 uid 发起请求
});

const goTo = (index) => {
    // 触发自定义事件，将 index 传递给父组件
    emit('changePage', index);
};


const open = () => {
  ElMessageBox.prompt('请输入您的新用户名', '设置用户名', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    inputPattern:
    /^(?!\d+$)[a-zA-Z0-9\u4e00-\u9fa5]+$/,
    inputErrorMessage: '用户名格式错误，中英文、数字，且不能为纯数字',
  })
    .then(({ value }) => {
      ElMessage({
        type: 'success',
        message: `您的新用户名:${value}已提交`,
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}
</script>

<template>
    <div class="pageWrapper">
        <div class="avatar" @mouseenter="state.showUpload = true" @mouseleave="state.showUpload = false">
            <img class="avatar-icon" src="../assets/img/static/tmp_user.jpg" alt="">
            <!-- 只在悬浮时显示 el-upload -->
            <el-upload v-if="state.showUpload" class="avatar-uploader"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="state.imageUrl" :src="state.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </div>
        <div class="user-info">
            <h1>Hi,<span style="margin-left: 20px;">{{ state.username }}</span></h1>
            <p>{{ state.telephone }}</p>
            <ul class="ucenter-list">
                <li class="ucenter-list-li" @click="goTo('/phone')">
                    <div class="title">我的绑定手机<img src="../assets/img/index/success.png" alt=""></div>
                    <div class="content">手机已绑定，账号安全保障中</div>
                    <div class="link">去查看></div>
                </li>
                <li class="ucenter-list-li" @click="goTo('/password')">
                    <div class="title">我的账号密码<img src="../assets/img/index/success.png" alt=""></div>
                    <div class="content">密码已设置，账号安全保障中</div>
                    <div class="link">去修改></div>
                </li>
                <li class="ucenter-list-li" @click="goTo('/records')">
                    <div class="title">我的登录记录<img src="../assets/img/index/attention.png" alt=""></div>
                    <div class="content">登录记录可前往查看...</div>
                    <div class="link">去查看</div>
                </li>
                <li class="ucenter-list-li" @click="open">
                    <div class="title">我的用户名<img src="../assets/img/index/success.png" alt=""></div>
                    <div class="content">用户名已设置，可用于登录</div>
                    <div class="link">去更改></div>
                </li>
            </ul>
        </div>
    </div>
</template>

<style scoped>
@import "../assets/css/account.css";
</style>